package com.xyy.saas.payment.util;

import com.alibaba.fastjson.JSON;
import com.xyy.framework.redis.core.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author wuqiongda
 * @date 2019/12/29
 */
@Component
public class DistributedRedisLock implements ApplicationContextAware {

    private static ApplicationContext context;
    /**
     * redis 实现分布式重入锁
     *
     * @param key
     * @param value
     * @param seconds  过期倒计时的秒数(－1代表永不过期)
     * @since 1.0
     */
    public boolean reentrantLock(final String key, final String value, final int seconds) {
        if (key == null || StringUtils.isEmpty(String.valueOf(key)) || value == null) {
            return false;
        }
        List<String> list = new ArrayList<>();
        list.add(value);
        List<String> keys = new ArrayList<String>();
        keys.add(key);
        boolean flag = false;
        try {
            String script = "if redis.call('set',KEYS[1],ARGV[1],'NX','EX',ARGV[2]) then return 1 elseif redis.call('get',KEYS[1])==ARGV[1] then if redis.call('expire',KEYS[1],ARGV[2]) then return 1 end end return 0";
            Object result = getRedisClient().eval(script, keys, list);
            if ("1".equals(String.valueOf(result))) {
                flag = true;
            }
            return flag;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * redis 解锁
     *
     * @param key
     */
    public int unlock(final String key, String value) {
        try {
            long start = System.currentTimeMillis();
            String script = "if redis.call('get', KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            Object result = getRedisClient().eval(script, Collections.singletonList(key), Collections.singletonList(JSON.toJSONString(value)));
            return Integer.valueOf(String.valueOf(result));
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    private static RedisClient getRedisClient() {
        return (RedisClient) context.getBean("redisClient");
    }
}
